import {Platform, PLATFORM} from "./Platform";
import Type = cc.Sprite.Type;
import Sprite = cc.Sprite;


export const delay = (d: number) => new Promise(r => setTimeout(r, d));


/**
 * 将数字转换为 二位数字 10以下 标为 0X
 * @param s
 */
export function padTwo(s: number) {
    if (s < 10) {
        return '0' + s;
    } else {
        return s;
    }
}

/**
 * 将秒数转变为  00:00 结构
 * @param t
 */
export function secondToMinuteString(t: number): string {
    let a = Math.floor(t / 60), b = t % 60;
    // return `${padTwo(a)} : ${padTwo(b)}`;
    return `${padTwo(a)}'${padTwo(b)}''`;

}

/**
 * 将秒数转变为  00:00 结构
 * @param t
 */
export function secondToMinuteStringP(t: number): string {
    let a = Math.floor(t / 60), b = t % 60;
    return `${padTwo(a)}'${padTwo(b)}''`;
}

export function dateToDateString(date: Date = new Date()) {
    console.log(date);
    return `${date.getFullYear()}${padTwo(date.getMonth() + 1)}${padTwo(date.getDate())}`;
}


export function ToDateString(date: Date = new Date()) {
    console.log(date);
    return `${date.getFullYear()}${padTwo(date.getMonth() + 1)}${padTwo(date.getDate())}`;
}


/**
 * 数字进阶方法 B / M /K
 * @param n
 */
export function formatNumber(n: number) {
    if (n > 1_200_000_000) {
        return (n / 1000_000_000).toFixed(1) + 'B'
    } else if (n > 1_200_000) {
        return (n / 1000_000).toFixed(1) + 'M'
    } else if (n > 1_200) {
        return (n / 1000).toFixed(1) + 'K'
    } else {
        return String(n);
    }
}

/**
 * 加载图片
 * @param sprite 要展示的图片组件
 * @param url  URL
 */
export function loadImage(sprite: cc.Sprite, url: string) {
    if (PLATFORM == Platform.WECHAT) {
        setAvatar(sprite, url);
        return;
    }
    if (url)
        cc.assetManager.loadRemote<cc.Texture2D>(url, {ext: '.png'}, ((err, asset) => {
            sprite.spriteFrame = new cc.SpriteFrame(asset);
        }));
    // cc.loader.load(url, (err, texture) => {
    //     sprite.spriteFrame = new cc.SpriteFrame(texture);
    // });
}


/**
 * 手机号格式验证
 * @param mobile
 */
export function isMobile(mobile) {
    let regMobile = /^1[0-9]{10}$/;
    if (regMobile.test(mobile)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 邮箱格式验证
 * @param email
 */
export function isEmail(email) {//邮箱格式
    // let num = /^\w+@[a-z0-9]+\.[a-z]+$/i;
    let num = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/i;
    if (num.test(email)) {
        return true;
    }
    return false;
}

/**
 * name超过count的以end形式展现
 * @param count  字数限制
 * @param name   文字
 * @param end    结尾方式
 * @constructor
 */
export function OmitName(count: number, name: string, end: string = '...') {
    let a = '';
    if (name.length > count) {
        for (let i = 0; i < count; i++) {
            a += name[i];
        }
        a += end;
    } else {

        a = name;
    }
    return a;
}

/**
 * 加载图片（微信用）
 * @param sprite   显示的载体
 * @param avatarUrl url
 */
export function setAvatar(sprite: cc.Sprite, avatarUrl: string) {
    if (PLATFORM == Platform.WECHAT) {
        let image = wx.createImage();
        image.onerror = e => console.log(e);
        image.onload = () => {
            try {
                let texture = new cc.Texture2D();
                // @ts-ignore
                texture.initWithElement(image);
                texture.handleLoadedTexture();
                sprite.spriteFrame = new cc.SpriteFrame(texture);

            } catch (e) {
                // console.warn(e);
            }
        };
        image.src = avatarUrl;
    } else {
        loadImage(sprite, avatarUrl);
    }

}


/**
 * 加载本地图片
 * @param s
 * @param l
 * @param c
 */
export function loadLevelImage(s: cc.Sprite, l, c) {  // resources/level0/000000

    cc.resources.load('level' + l + '/' + c, cc.SpriteFrame, function (err, spriteFrame: cc.SpriteFrame) {
        if (err) {
            cc.error(err.message || err);
            // s.spriteFrame = G.res.frontIcons[0];
            return;
        }
        s.spriteFrame = spriteFrame;
    })


}


/**
 * Fisher-Yates Shuffle 随机置乱算法
 * @param array 目标数组
 */
export function fisherYatesShuffle(array: any[]): any[] {
    let count = array.length;
    while (count) {
        let index = Math.floor(Math.random() * count--);
        let temp = array[count];
        array[count] = array[index];
        array[index] = temp;
    }
    return array;
}


export enum LoadImageType {
    All,
    Width,
    Height
}

/**
 * 自适应加载图片（仅适用于web等，无法用于加载微信头像）
 * @param sprite  加载图片显示的载体
 * @param url     加载图片的路径
 * @param node    加载图片所需大小的对应节点（处于格子里的一般此节点指格子）
 * @param spacing 图片与格子的间距，默认为0，需根据实际情况调整
 * @param type    自适应类型
 */
export async function loadImageAuto(sprite: cc.Sprite, url: string, node: cc.Node, spacing: number = 0, type: LoadImageType = LoadImageType.All): Promise<boolean> {
    // console.log(url);
    if (url) {

        cc.assetManager.loadRemote<cc.Texture2D>(url, {ext: '.png'}, ((err, asset) => {

            if (err) {

                console.log(err);
                return false;
            }

            sprite.type = Type.SIMPLE;
            sprite.sizeMode = Sprite.SizeMode.CUSTOM;

            let spriteFrame = new cc.SpriteFrame(asset);
            let width = spriteFrame.getRect().width;
            let height = spriteFrame.getRect().height;
            let number = width / (node.width - spacing);
            let number1 = height / (node.height - spacing);
            switch (type) {
                case LoadImageType.All:
                    if (number > number1) {
                        sprite.node.height = height / number;
                        sprite.node.width = node.width - spacing;

                    } else if (number < number1) {
                        sprite.node.height = node.height - spacing;
                        sprite.node.width = width / number1;
                    } else {
                        sprite.node.height = node.height - spacing;
                        sprite.node.width = node.width - spacing;
                    }
                    break;
                case LoadImageType.Width:
                    sprite.node.height = height / number;
                    sprite.node.width = node.width - spacing;
                    break;
                case LoadImageType.Height:
                    sprite.node.height = node.height - spacing;
                    sprite.node.width = width / number1;
                    break;
            }


            sprite.spriteFrame = spriteFrame;
            return true;
        }));
    } else {

        return false
    }

}


/**
 * 加载本地奖励图片
 * @param s   图片
 * @param l  名称
 */
export function loadRewardImage(s: cc.Sprite, l) {  // resources/reward/money

    cc.resources.load('reward/' + l, cc.SpriteFrame, function (err, spriteFrame: cc.SpriteFrame) {
        if (err) {
            cc.error(err.message || err);
            // s.spriteFrame = G.res.frontIcons[0];
            return;
        }
        s.spriteFrame = spriteFrame;
    })
}

/**
 * 加载本地图片
 * @param sprite   图片
 * @param l  名称
 * @param node
 * @param spacing
 * @param type
 */
export function loadRewardAutoImage(sprite: cc.Sprite, l, node: cc.Node, spacing: number = 0, type: LoadImageType = LoadImageType.All) {  // resources/reward/money

    cc.resources.load('reward/' + l, cc.SpriteFrame, function (err, spriteFrame: cc.SpriteFrame) {
        if (err) {
            cc.error(err.message || err);
            // s.spriteFrame = G.res.frontIcons[0];
            return;
        }
        sprite.type = Type.SIMPLE;
        sprite.sizeMode = Sprite.SizeMode.CUSTOM;
        // let spriteFrame = new cc.SpriteFrame(asset);
        let width = spriteFrame.getRect().width;
        let height = spriteFrame.getRect().height;
        let number = width / (node.width - spacing);
        let number1 = height / (node.height - spacing);
        switch (type) {
            case LoadImageType.All:
                if (number > number1) {
                    sprite.node.height = height / number;
                    sprite.node.width = node.width - spacing;

                } else if (number < number1) {
                    sprite.node.height = node.height - spacing;
                    sprite.node.width = width / number1;
                } else {
                    sprite.node.height = node.height - spacing;
                    sprite.node.width = node.width - spacing;
                }
                break;
            case LoadImageType.Width:
                sprite.node.height = height / number;
                sprite.node.width = node.width - spacing;
                break;
            case LoadImageType.Height:
                sprite.node.height = node.height - spacing;
                sprite.node.width = width / number1;
                break;
        }


        sprite.spriteFrame = spriteFrame;
    })
}

/**
 * 加载本地图片
 * @param s   图片
 * @param l  名称
 */
export function loadLocalImage(s: cc.Sprite, l) {  // resources/reward/money

    cc.resources.load(l, cc.SpriteFrame, function (err, spriteFrame: cc.SpriteFrame) {
        if (err) {
            cc.error(err.message || err);
            // s.spriteFrame = G.res.frontIcons[0];
            return;
        }
        s.spriteFrame = spriteFrame;
    })
}


/**
 * 加载本地鱼图片
 * @param s   图片
 * @param l  名称
 */
export function loadFishImage(s: cc.Sprite, l) {  // resources/reward/money

    cc.resources.load('fish/fish/' + l, cc.SpriteFrame, function (err, spriteFrame: cc.SpriteFrame) {
        if (err) {
            cc.error(err.message || err);
            // s.spriteFrame = G.res.frontIcons[0];
            return;
        }
        s.spriteFrame = spriteFrame;
    })
}

/**
 * 加载本地图片
 * @param sprite   图片
 * @param l  名称
 * @param node
 * @param spacing
 * @param type
 */
export function loadFishAutoImage(sprite: cc.Sprite, l, node: cc.Node, spacing: number = 0, type: LoadImageType = LoadImageType.All) {  // resources/reward/money

    cc.resources.load('fish/fish/' + l, cc.SpriteFrame, function (err, spriteFrame: cc.SpriteFrame) {
        if (err) {
            cc.error(err.message || err);
            // s.spriteFrame = G.res.frontIcons[0];
            return;
        }
        sprite.type = Type.SIMPLE;
        sprite.sizeMode = Sprite.SizeMode.CUSTOM;
        // let spriteFrame = new cc.SpriteFrame(asset);
        let width = spriteFrame.getRect().width;
        let height = spriteFrame.getRect().height;
        let number = width / (node.width - spacing);
        let number1 = height / (node.height - spacing);
        switch (type) {
            case LoadImageType.All:
                if (number > number1) {
                    sprite.node.height = height / number;
                    sprite.node.width = node.width - spacing;

                } else if (number < number1) {
                    sprite.node.height = node.height - spacing;
                    sprite.node.width = width / number1;
                } else {
                    sprite.node.height = node.height - spacing;
                    sprite.node.width = node.width - spacing;
                }
                break;
            case LoadImageType.Width:
                sprite.node.height = height / number;
                sprite.node.width = node.width - spacing;
                break;
            case LoadImageType.Height:
                sprite.node.height = node.height - spacing;
                sprite.node.width = width / number1;
                break;
        }


        sprite.spriteFrame = spriteFrame;
    })
}


/**
 * 加载本地渔具图片
 * @param s   图片
 * @param l  名称
 * @param n  id
 */
export function loadFishhookImage(s: cc.Sprite, l, n) {  // resources/reward/money

    cc.resources.load('fish/' + l + '/' + n, cc.SpriteFrame, function (err, spriteFrame: cc.SpriteFrame) {
        if (err) {
            cc.error(err.message || err);
            // s.spriteFrame = G.res.frontIcons[0];
            return;
        }
        s.spriteFrame = spriteFrame;
    })
}


/**
 * 加载本地渔具图片
 * @param sprite   图片
 * @param l  名称
 * @param n  id
 * @param node
 * @param spacing
 * @param type
 */
export function loadFishhookAutoImage(sprite: cc.Sprite, l, n, node: cc.Node, spacing: number = 0, type: LoadImageType = LoadImageType.All) {  // resources/reward/money

    cc.resources.load('fish/' + l + '/' + n, cc.SpriteFrame, function (err, spriteFrame: cc.SpriteFrame) {
        if (err) {
            cc.error(err.message || err);
            // s.spriteFrame = G.res.frontIcons[0];
            return;
        }
        sprite.type = Type.SIMPLE;
        sprite.sizeMode = Sprite.SizeMode.CUSTOM;
        // let spriteFrame = new cc.SpriteFrame(asset);
        let width = spriteFrame.getRect().width;
        let height = spriteFrame.getRect().height;
        let number = width / (node.width - spacing);
        let number1 = height / (node.height - spacing);
        switch (type) {
            case LoadImageType.All:
                if (number > number1) {
                    sprite.node.height = height / number;
                    sprite.node.width = node.width - spacing;

                } else if (number < number1) {
                    sprite.node.height = node.height - spacing;
                    sprite.node.width = width / number1;
                } else {
                    sprite.node.height = node.height - spacing;
                    sprite.node.width = node.width - spacing;
                }
                break;
            case LoadImageType.Width:
                sprite.node.height = height / number;
                sprite.node.width = node.width - spacing;
                break;
            case LoadImageType.Height:
                sprite.node.height = node.height - spacing;
                sprite.node.width = width / number1;
                break;
        }


        sprite.spriteFrame = spriteFrame;
    })
}

export function loadSpFish(name:string) {
    console.log('加载');

    cc.resources.load('fishSp/'+name+'/skeleton' ,  function (err, s) {
        if (err) {
            console.log('报错啦');

            cc.error(err.message || err);
            // s.spriteFrame = G.res.frontIcons[0];
            return;
        }
        console.log(s);


    })
}


/**
 * 等分数组，尽量等分数组，保证单个数值不小于1， 如把6进行5等分  [2,1,1,1,1]
 * @param num    等分数值
 * @param count  分为几个
 */
export function halvingNum(num: number, count: number = 5): number[] {
    let n = [];
    if (num > count) {
        if (num % count == 0) {
            for (let i = 0; i < count; i++) {
                n.push(num / count);
            }
        } else {
            for (let i = 0; i < count; i++) {
                n.push(i < num % count ? (num / count + 1) : (num / count));
            }
        }
    } else {
        for (let i = 0; i < num; i++) {
            n.push(1);
        }
    }
    return n;
}

/**
 * 计算时间差
 * @param date1  目标时间  格式为  2023-04-15T15:14:52.847
 * @param date2  现在时间，默认不填
 */
export function calculateTimeOfPlant(date1, date2 = new Date().getTime()) {
    console.log('计算时间');
    console.log(date2);
    console.log(date1);
    // let split2 = date2.split('T');
    let split1 = date1.split('T');
    // date2 = split2[0] + ' ' + split2[1];
    date1 = split1[0] + ' ' + split1[1];

    // var dateStr = '2022-01-01';
    date1 = date1.replace(/\-/g, '/'); // 将'-'符号替换成'/'
    date1 = date1.split('.')[0];

    // var dataTime = new Date(dateStr).getTime();
    console.log(date1);

    var date3 = new Date(date1).getTime() - date2;   //时间差的毫秒数
    console.log(date2)
    console.log(new Date(date1).getTime())
    console.log(date3);

    //------------------------------

    //计算出相差天数
    var days = Math.floor(date3 / (24 * 3600 * 1000))

    //计算出小时数

    var leave1 = date3 % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000))
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000))
    //计算相差秒数
    var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000)
    console.log(" 相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒 " + date3);

    cc.log(" 相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒 " + date3)
    return days * 24 * 3600 + hours * 3600 + minutes * 60 + seconds;
}

export function calculateTimeOfRipe(date2, date1) {
    let split2 = date2.split('T');
    let split1 = date1.split('T');

    date2 = split2[0] + ' ' + split2[1];
    date1 = split1[0] + ' ' + split1[1];

    date1 = date1.replace(/\-/g, '/'); // 将'-'符号替换成'/'
    // date1.splice(date1.length-5,4);
    date1 = date1.split('.')[0];


    date2 = date2.replace(/\-/g, '/'); // 将'-'符号替换成'/'
    // date2.splice(date2.length-5,4);
    date2 = date2.split('.')[0];


    var date3 = new Date(date2).getTime() - new Date(date1).getTime();   //时间差的毫秒数

    //------------------------------

    //计算出相差天数
    var days = Math.floor(date3 / (24 * 3600 * 1000))

    //计算出小时数

    var leave1 = date3 % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000))
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000))
    //计算相差秒数
    var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000)
    // cc.log(" 相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒 " + date3)
    // console.log(days * 24 * 3600 + hours * 3600 + minutes * 60 + seconds);
    return days * 24 * 3600 + hours * 3600 + minutes * 60 + seconds;
}

/**
 * 返回时间 天 时 分 秒
 * @param t  毫秒
 */
export function backTimeOfLand(t) {
    //计算出相差天数
    var days = Math.floor(t / (24 * 3600))

    //计算出小时数

    var leave1 = t % (24 * 3600)    //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600))
    //计算相差分钟数
    var leave2 = leave1 % (3600)        //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60))
    //计算相差秒数
    var leave3 = leave2 % (60)      //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3)
    // cc.log(" 相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒 " + date3)
    // console.log(days * 24 * 3600 + hours * 3600 + minutes * 60 + seconds);
    // return days * 24 * 3600 + hours * 3600 + minutes * 60 + seconds;
    return `${days}天${hours}时${minutes}分${seconds}秒`;
}


export function deepClone(obj) {
    if (typeof obj !== 'object' || obj == null) { // obj==null相当于obj===null || obj===undefined
        // obj为null或undefined或者不是对象不是数组，则直接返回
        return obj
    }

    // 初始化返回结果
    let result
    if (obj instanceof Array) {
        result = []
    } else {
        result = {}
    }
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) { // 保证key不是从原型继承来的
            result[key] = this.deepClone(obj[key]) // 递归调用
        }
    }
    return result // 返回结果
}



export class NodeBorder {
    top: number;
    bottom: number;
    left: number;
    right: number;

    constructor(top: number, bottom: number, left: number, right: number) {
        this.top = top;
        this.bottom = bottom;
        this.left = left;
        this.right = right;
    }
}

export function getBorder(node: cc.Node): NodeBorder {
    const p = node.convertToWorldSpaceAR(cc.v2(0, 0));
    return new NodeBorder(
        p.y + node.height / 2,
        p.y - node.height / 2,
        p.x - node.width / 2,
        p.x + node.width / 2
    );
}

export function inBorder(b: NodeBorder, p: { x: number, y: number }) {
    return p.x > b.left &&
        p.x < b.right &&
        p.y > b.bottom &&
        p.y < b.top;
}


/**
 * 返回一个数组的指定数量的不同索引
 * @param arr  数组
 * @param n 索引数量
 */
export function backByCount<T>(arr: T[],n:number):number[]{
    if(arr.length == 0 || n == 0){
        return undefined
    }
    if(arr.length < n){
        let aa = [];
        for (let i = 0; i < arr.length; i++) {
            aa.push(i);
        }
        return aa;
    }
    // array.map()
    let a = [];
    for (let i = 0; i < n; i++) {
        // @ts-ignore
        let number = backOne(arr,a);
        a.push(number);
    }
    return a;
}

export function backOne(array:[],a:[]):number{
    let number = Math.floor(Math.random()*array.length);
    // @ts-ignore
    if(a.includes(number)){
        return  backOne(array,a);
    }else {
        return number;
    }

}

export function backABCD(data: string) {
    switch (data) {
        case 'A':
            return 0;
        case 'B':
            return 1;
        case 'C':
            return 2;
        case 'D':
            return 3;
    }
}